from sanic.views import HTTPMethodView
from sanic.response import text,json
from processing.comm import sqlPaging,sqlOrder,set_status,timestamp_to_standard
from processing.Sql_DataFrom import ProJosn
class wechatList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = request.args.get('keyword', '')

        try:

           #  sql = f"""
           #      select us.id,us.nickName,us.openid,us.head_img,us.phone,us.create_time,re.residue from
           #      rechargerecord re left join c_users us on re.openid=us.openid
           #      where re.merchant_id='{user_id}' and re.residue > 0
           # """

            sql = f"""
                    select id,nickName,openid,head_img,phone,create_time from c_users where merchant_id='{user_id}'
                """

            tol = f""" SELECT COUNT(*) FROM c_users where merchant_id='{user_id}' """

            if keyword:
                sql += f" and  nickName LIKE '%{keyword}%' or openid LIKE '%{keyword}%' "
                tol += f" and  nickName LIKE '%{keyword}%' or openid LIKE '%{keyword}%' "

            # sql += " GROUP BY openid "
            sql = sqlOrder(sql, 'create_time', 'DESC')
            sql = sqlPaging(pageNum, pageSize, sql)
            data = db.find_all(sql)
            tol_data = db.find_one(tol)
            if data:
                titleList = ['id','nickName','openid','head_img','phone','create_time']
                data = ProJosn(data, titleList,'list')
            else:
                data = []
            return json({'code': 200, 'message': "请求成功!", 'data': {'list':data,'total':tol_data[0]}})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/wechatApi/wechatList', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class wechatDelete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:

            sql = "delete from c_users where id=%s"

            db.delete(sql, (html_data['id']))

            return json({'code': 200, 'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/wechatApi/wechatDelete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)



class setAddress(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:
            sql = """
               insert into user_address(merchant_id,address,user_use,openid,details,utime,ctime) VALUES(%s,%s,%s,%s,%s,now(),now())
           """

            db.insert(sql, (
                user_id,
                html_data['address'],
                html_data['user_use'] or 2,
                html_data['openid'],
                html_data['details']
            ))

            return json({'code': 200, 'message': "请求成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/wechatApi/setAddress', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


class findAddress(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        openid = request.args.get('openid', '')
        address_id = int(request.args.get('address_id', 0))
        sql = f"""
            select id,address,details,latitude,longitude from user_address where merchant_id='{user_id}' and openid='{openid}' and id={address_id}
        """

        addressData = db.find_all(sql)

        result = ProJosn(addressData,sql)
        if result:
            pass
        else:
            result = []
        data = {
            'code': 200,
            'data':{
              'list':result
            },
            'message': '请求成功!'
        }
        return json(data)